package org.luxor.eshop.storage.service;

import io.seata.spring.annotation.GlobalTransactional;
import org.luxor.commons.core.exception.TransactionException;
import org.luxor.commons.core.utils.BeanUtils;
import org.luxor.commons.core.utils.CollectionUtils;
import org.luxor.eshop.storage.entity.CommodityEntity;
import org.luxor.eshop.storage.entity.dto.CommodityDto;
import org.luxor.eshop.storage.entity.dto.DeductInventoryDto;
import org.luxor.eshop.storage.mapper.CommodityMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * 仓储服务
 *
 * @author Mr.Yan  @date: 2020/11/24
 */
@Service
public class StorageService {

    @Resource
    private CommodityMapper commodityMapper;

    /**
     * 扣减库存数量
     */
    @GlobalTransactional(rollbackFor = TransactionException.class)
    @Transactional(rollbackFor = TransactionException.class)
    public void deduct(Collection<DeductInventoryDto> deductInventory) {
        if (CollectionUtils.isEmpty(deductInventory)) {
            return;
        }
        for (DeductInventoryDto val : deductInventory) {
            commodityMapper.deductInventory(val.getQuantity(), val.getCommodityCode());
        }
    }

    /**
     * 根据编号获得商品信息
     *
     * @param commodityCode 商品编号
     * @return 商品信息
     */
    public CommodityDto getByCommodityCode(String commodityCode) {
        CommodityEntity commodityEntity = commodityMapper.getByCommodityCode(commodityCode);
        return BeanUtils.transform(CommodityDto.class, commodityEntity);
    }
}
